package com.hong.tomcat;

import com.hong.util.WebLoaderUtil;

import javax.servlet.Servlet;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by John on 2019/1/31.
 * 处理请求任务
 */
public class SocketProcess implements Runnable {
    protected Socket socket;

    public SocketProcess(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());

            /**
             * 根据请求URL，调用servlet，执行业务逻辑
             * 解析http请求，拿到请求所对应的项目，发起servlet调用
             * GET /servlet-study-0.0.1 HTTP/1.1
             */
            WebXml webXml = WebLoaderUtil.resultMap.get(request.getApplication());
            Servlet servlet = webXml.servletInstances.get(webXml.servletMapping.get(request.getUrl()));

            servlet.service(request, response);

            String res = "Hello Tomcat!";

            /**
             *  创建用于返回浏览器的对象
             *  响应结果 200 符合HTTP协议
             *
             *  请求行
             *  请求头
             *  空行
             *  请求体
             */
            StringBuilder sb = new StringBuilder();
            sb.append("HTTP/1.1 200 OK\r\n");
            sb.append("Content-Type: text/html\r\n");
            sb.append("Content-Length: " + res.length() + "\r\n");
            sb.append("\r\n");
            sb.append(res);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(sb.toString().getBytes());
            outputStream.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    //关闭一次请求的socket,因为http请求就是采用短连接的方式
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
